<h1>Term: <%=h @term.name %></h1>

<% if @message %>
<p><%= @message %></p>
<% else %>
<script type="text/javascript">
function fetchRemote(department_name, status_id, target_uri) {
    new Ajax.Request('sync_department', {
		parameters: {
		    department: department_name,
		    uri: target_uri,
		    debug: true
		},
		onLoading: function() {
		    if (target_uri) {
		        document.getElementById(status_id).innerText = 'fetching ' + target_uri
		    } else {
		        document.getElementById(status_id).innerText = 'fetching the first page...'
	        }
		},
		onSuccess: function(transport) {
		    response = transport.responseText.evalJSON()
		    if (response['error']) {
		        document.getElementById(status_id).innerHTML = '<i class="error">' + response['error'] + '</i>';
		    } else {
		        document.getElementById(status_id).innerText = 'OK'
		        if (response['next_uri'])
		            fetchRemote(department_name, status_id, response['next_uri'])
	        }
		},
		onFailure: function(transport) {
		    document.getElementById(status_id).innerHTML =
		        '<i class="error">HTTP request failed locally:' + transport.status + '</i>';
		}
	})
}
</script>
<table id="sync_table">
<thead>
    <tr>
    <td> Department </td>
    <td> Abbreviations </td>
    <td> Status </td>
    </tr>
</thead>
<tbody>
<% @departments.each do |dept|
    id = dept.downcase.gsub(/[\/\\,]/,'').split(/\s+/).join() %>
<tr>
<td><%= dept %></td>
<td><%= DepartmentAbbreviation.find_abbreviations(dept).join(', ') %></td>
<td id="<%= id %>"><a href="javascript:fetchRemote('<%= dept %>', '<%= id %>', null)">Start</a></td>
</tr>
<% end %>
</tbody>
</table>
<% end %>
<%= link_to 'Back', terms_path %>
